package org.vectrics.recruiter.user.resume.email;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;
import org.vectrics.user.PhoneNumber;
import org.vectrics.user.PhoneNumberSet;

public class PhoneNumberExtractorUS extends PhoneNumberExtractor {
	private Logger log = Logger.getLogger(this.getClass());
	public static String REGULAR_EXPRESSION = "([0-9]{3} [0-9]{3} [0-9]{4})|(\\([0-9]{3}\\)[0-9]{3}-[0-9]{4})|([0-9]{1}-[0-9]{3}-[0-9]{3}-[0-9]{4})|([0-9]{3}-[0-9]{3}-[0-9]{4})|([0-9]{3}-[0-9]{4})";

	public PhoneNumberExtractorUS() {
		super();
	}

	public PhoneNumberSet findPhoneNumbersInText(WordList wordList) {
		PhoneNumberSet phoneNumbers = new PhoneNumberSet();
		
		Object[] wordArray = wordList.toArray();
		
		for (int i = 0; i < wordArray.length; i++) {
			Word word = (Word)wordArray[i];
			if (word.getType().equals(Word.TYPE_WORD)) {
				if (word.getValue().matches(REGULAR_EXPRESSION)) {
					log.info("Adding to phone numbers: " + word.getValue());
					phoneNumbers.add(new PhoneNumber(word.getValue()));
				} else {
					addMultiWordPhoneNumber(i, wordArray, phoneNumbers);
				}
				
			} else {
				addMultiWordPhoneNumber(i, wordArray, phoneNumbers);
			}
		}
		return(phoneNumbers);
	}

	protected boolean addMultiWordPhoneNumber(int i, Object[] wordArray, Set phoneNumbers) {
		boolean phoneAdded = false;
		if (wordArray.length > i + 3) {
			Word word1 = (Word)wordArray[i];
			Word word2 = (Word)wordArray[i + 1];
			Word word3 = (Word)wordArray[i + 2];
			Word word4 = (Word)wordArray[i + 3];
		
			log.info("Looking at multi words to find phone number: " 
					+ word1 + ", "
					+ word2 + ", "
					+ word3 + ", "
					+ word4
					);
			if (
				(isStartBracket(word1)) &&
				(word2.getValue().length() == 3) &&
				(isEndBracket(word3)) &&
				(word4.getValue().length() == 9)
				) {
					String potentialPhoneNumber = word2.getValue() + word4.getValue();
					if (potentialPhoneNumber.matches(this.REGULAR_EXPRESSION)) {
						phoneAdded = true;
						phoneNumbers.add(new PhoneNumber(potentialPhoneNumber));
				}
			}
		}
		return(phoneAdded);
	}
	
	private boolean isStartBracket(Word word) {
		return((word.getValue().equals("(")) || (word.getValue().equals("[")));
	}
	private boolean isEndBracket(Word word) {
		return((word.getValue().equals(")")) || (word.getValue().equals("]")));
	}
	
}
